#include "NES_InputMapper.h"




NES_InputMapper::NES_InputMapper(){

  this->ButtonPressStatus=0U;

  for(int i=0;i<32;i++){
    this->captures.capture[i].Index=-1;
    this->captures.capture[i].Button=0U;
  }

}

NES_InputMapper::~NES_InputMapper(){
}

void NES_InputMapper::InputPress(int Index,uint32_t Button){
  int pos;

  pos=FindCapture(Index,Button);

  this->ButtonPressStatus=this->ButtonPressStatus|H_NES_CPP::StandardControllerStatus::PosToButton(pos);
}

void NES_InputMapper::InputRelease(int Index,uint32_t Button){
  int pos;

  pos=FindCapture(Index,Button);
  
  this->ButtonPressStatus=this->ButtonPressStatus&(~H_NES_CPP::StandardControllerStatus::PosToButton(pos));
}

int NES_InputMapper::SetKeyMapper(uint32_t KeyVal,int Index,uint32_t Button){
  int pos;

  pos=H_NES_CPP::StandardControllerStatus::ButtonToPos(KeyVal);

  if((pos<0)||(pos>31)){
    return -1;
  }

  captures.capture[pos].Index=Index;
  captures.capture[pos].Button=Button;

  this->ButtonPressStatus=this->ButtonPressStatus&(~H_NES_CPP::StandardControllerStatus::PosToButton(pos));

  return 0;
}

int NES_InputMapper::GetKeyMapper(uint32_t KeyVal,int* Index,uint32_t* Button){
  int pos;

  pos=H_NES_CPP::StandardControllerStatus::ButtonToPos(KeyVal);
  if((pos<0)||(pos>31)){
    return -1;
  }
  
  Index[0]=captures.capture[pos].Index;
  Button[0]=captures.capture[pos].Button;

  return 0;
}

int NES_InputMapper::SetKeyMapper_Array(QByteArray& mapdata){
  Captures captures;

  if(mapdata.size()!=sizeof(Captures)){
    return -1;
  }

  memcpy(&captures,mapdata.constData(),sizeof(Captures));

  this->captures=captures;

  return 0;
}

QByteArray NES_InputMapper::GetKeyMapper_Array(){

  char* captures=(char*)&this->captures;

  return QByteArray(captures,sizeof(Captures));
}

uint32_t NES_InputMapper::GetButtonPressStatus(){
  return ButtonPressStatus;
}

int NES_InputMapper::FindCapture(int Index,uint32_t Button){
  int r;
  Capture* capture;

  for(r=0;r<32;r++){
    
    capture=&captures.capture[r];
    
    if((capture->Button==Button)&&(capture->Index==Index)){
      return r;
    }
  }

  return -1;
}



